package com.vicene.gmail.ware.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.TypeReference;
import com.fasterxml.jackson.databind.ObjectReader;
import com.rabbitmq.client.Channel;
import com.vicene.gmail.common.mq.OrderTo;
import com.vicene.gmail.common.mq.StockDetailTo;
import com.vicene.gmail.common.mq.StockLockedTo;
import com.vicene.gmail.common.utils.R;
import com.vicene.gmail.ware.entity.WareOrderTaskDetailEntity;
import com.vicene.gmail.ware.entity.WareOrderTaskEntity;
import com.vicene.gmail.ware.exception.NoStockException;
import com.vicene.gmail.ware.feign.OrderFeignService;
import com.vicene.gmail.ware.feign.ProductFeignService;
import com.vicene.gmail.ware.service.WareOrderTaskDetailService;
import com.vicene.gmail.ware.service.WareOrderTaskService;
import com.vicene.gmail.ware.vo.*;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vicene.gmail.common.utils.PageUtils;
import com.vicene.gmail.common.utils.Query;

import com.vicene.gmail.ware.dao.WareSkuDao;
import com.vicene.gmail.ware.entity.WareSkuEntity;
import com.vicene.gmail.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;
import sun.security.util.ManifestEntryVerifier;

@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {


    @Autowired
    WareSkuDao wareSkuDao;

    @Autowired
    OrderFeignService orderFeignService;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    private WareOrderTaskService wareOrderTaskService;

    @Autowired
    private WareOrderTaskDetailService wareOrderTaskDetailService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    /**
     * 1,库存自动解锁
     * 下单成功，库存锁定成功，其他业务失败，回滚，之前锁定的库存自动解锁
     * 2，订单失败
     * @param to
     * @param message
     * @param channel
     */
    @Override
    public void unLockStock(StockLockedTo to)  {
        Long id = to.getId();
        StockDetailTo detail = to.getDetailTo();
        Long detailId = detail.getId();
        /**
         * 解锁
         * 1，查询数据库关于这个订单的锁定库存信息
         * 有证明库存锁定成功
         *      解锁：1）没有这个订单，必须解锁
         *           2）有订单，（已取消，解锁） （没取消，不解锁）
         * 没有无需解锁
         */
        WareOrderTaskDetailEntity byId = wareOrderTaskDetailService.getById(detailId);
        if(byId != null){
            //解锁
            //Long id = to.getId();
            WareOrderTaskEntity taskEntity = wareOrderTaskService.getById(id);
            String orderSn = taskEntity.getOrderSn();
            R r = orderFeignService.getOrderStatus(orderSn);
            if(r.getCode() == 0){
                OrderVo data  = (OrderVo) r.getData(new TypeReference<OrderVo>(){});
                if(data == null || data.getStatus() == 4){

                    if(byId.getLockStatus() == 1){
                        //订单已经被取消，需要解锁
                        wareSkuDao.unLockStock(detail.getSkuId() , detail.getWareId() , detail.getSkuNum() );
                        //更新库存工作单的状态
                        WareOrderTaskDetailEntity entity = new WareOrderTaskDetailEntity();
                        entity.setId(detailId);
                        entity.setLockStatus(2);
                        wareOrderTaskDetailService.updateById(entity);
                    }
                }
            }else {
                //抛出异常，让其他服务重新消费
                throw new RuntimeException("orderFeignService远程服务调用失败");

            }
        }else{
            //无需解锁
        }
    }

    @Transactional
    @Override
    public void unLockStock(OrderTo orderTo) {
        String orderSn = orderTo.getOrderSn();
        WareOrderTaskEntity task = wareOrderTaskService.getOrderTaskByOrderSn(orderSn);
        Long id = task.getId();
        List<WareOrderTaskDetailEntity> entities = wareOrderTaskDetailService.list(
                new QueryWrapper<WareOrderTaskDetailEntity>().eq("task_id" , id).eq("lock_status" ,1));
        for(WareOrderTaskDetailEntity entity : entities){
            wareSkuDao.unLockStock(entity.getSkuId() , entity.getWareId() , entity.getSkuNum() );
        }


    }


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        /**
         * skuId: 1
         * wareId: 2
         */
        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        if(!StringUtils.isEmpty(skuId)){
            queryWrapper.eq("sku_id",skuId);
        }

        String wareId = (String) params.get("wareId");
        if(!StringUtils.isEmpty(wareId)){
            queryWrapper.eq("ware_id",wareId);
        }


        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //1、判断如果还没有这个库存记录新增
        List<WareSkuEntity> entities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if(entities == null || entities.size() == 0){
            WareSkuEntity skuEntity = new WareSkuEntity();
            skuEntity.setSkuId(skuId);
            skuEntity.setStock(skuNum);
            skuEntity.setWareId(wareId);
            skuEntity.setStockLocked(0);
            //TODO 远程查询sku的名字，如果失败，整个事务无需回滚
            //1、自己catch异常
            //TODO 还可以用什么办法让异常出现以后不回滚？高级
            try {
                R info = productFeignService.info(skuId);
                Map<String,Object> data = (Map<String, Object>) info.get("skuInfo");

                if(info.getCode() == 0){
                    skuEntity.setSkuName((String) data.get("skuName"));
                }
            }catch (Exception e){

            }


            wareSkuDao.insert(skuEntity);
        }else{
            wareSkuDao.addStock(skuId,wareId,skuNum);
        }

    }

    @Override
    public List<SkusHasStockVo> getSkusHasStock(List<Long> skuIds) {

        List<SkusHasStockVo> collect = skuIds.stream().map(skuId -> {
            SkusHasStockVo vo = new SkusHasStockVo();

            Long count = baseMapper.getSkuStock(skuId);
            vo.setSkuId(skuId);
            vo.setHasStock((count != null && count > 0 ) ? true : false);
            return vo;
        }).collect(Collectors.toList());

        return collect;
    }

    @Transactional
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {

        //TODO 按照下单的收货地址，找到一个就近仓库，锁定库存。

        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(vo.getOrderSn());
        wareOrderTaskService.save(taskEntity);
        //找到每个商品在哪个仓库都有库存
        List<OrderItemVo> locks = vo.getLocks();
        List<SkuWareHasStock> collect = locks.stream().map(item ->{
            SkuWareHasStock stock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            stock.setSkuId(skuId);
            stock.setNum(item.getCount());
            List<Long> wareIds = wareSkuDao.listWareIdHasSkuStock(skuId);
            stock.setWareId(wareIds);
            return stock;
        }).collect(Collectors.toList());

        Boolean allLock = true;
        //锁定库存
        for(SkuWareHasStock hasStock : collect){
            Boolean skuStocked = false;
            Long skuId = hasStock.getSkuId();
            List<Long> wareIds = hasStock.getWareId();
            if(CollUtil.isEmpty(wareIds)){
                //没有任何库存有这个商品的库存
                throw new NoStockException(skuId);
            }
            for(Long wareId : wareIds){
                //成功返回1 ， 否则0
                Long count = wareSkuDao.lockSkuStock(skuId , wareId ,hasStock.getNum());
                if(count == 1){
                    skuStocked = true;

                    //TODO 告诉MQ库存锁定成功
                    WareOrderTaskDetailEntity entity =
                            new WareOrderTaskDetailEntity(null , skuId,"" , hasStock.getNum(), taskEntity.getId(),wareId , 1 );
                    wareOrderTaskDetailService.save(entity);
                    StockLockedTo lockedTo = new StockLockedTo();
                    lockedTo.setId(taskEntity.getId());

                    StockDetailTo stockDetailTo = new StockDetailTo();
                    BeanUtils.copyProperties(entity , stockDetailTo);
                    lockedTo.setDetailTo(stockDetailTo);
                    rabbitTemplate.convertAndSend("stock-event-exchange","stock.locked",lockedTo);
                }else{
                    //当前仓库锁失败，重试下一个仓库
                    skuStocked = false;

                    break;

                }

            }
            if(skuStocked == false){
                throw new NoStockException(skuId);
            }
        }
        return true;
    }



    @Data
    class SkuWareHasStock{
        private Long skuId;
        private List<Long> wareId;
        private Integer num;
    }
}